﻿using NewRen.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace NewRen.Schemas
{
    public class AccessBusinessEditProdutAttribute : BaseAuthAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            using (var db = new DB())
            {
                var id = 0;
                if (((MvcHandler)httpContext.Handler).RequestContext.RouteData.Values["id"] != null)
                    id = Convert.ToInt32(((MvcHandler)httpContext.Handler).RequestContext.RouteData.Values["id"]);
                else
                    id = Convert.ToInt32(httpContext.Request.Form["id"]);
                var product = db.Products.Find(id);
                if (product == null)
                {
                    return false;
                }
                if (!string.IsNullOrEmpty(httpContext.User.Identity.Name))
                {
                    var bussiness = db.Businesses.Where(ug => ug.LoginName == httpContext.User.Identity.Name).FirstOrDefault();
                    if (bussiness == null)
                    {
                        return false;
                    }
                    if (product.BusinessID != bussiness.ID)
                    {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
